var index = 0,
    menuIndex = 0,
    timer = null,
    pics = byId("banner").getElementsByTagName("div"),
    dots = byId("dots").getElementsByTagName("span"),
    menuItem = byId("menu-content").getElementsByTagName("div"),
    subMenu = byId("sub-menu"),
    innerBox = subMenu.getElementsByClassName("inner-box"),
    menus = menuItem.length,
    prev = byId("prev"),//上一张
    next = byId("next"),//下一张
    size = pics.length;
function slideImg() {
    var menuContent = byId("menu-content");
    //点击下一张按钮显示下一张图片
    addHandler(next, "click", function () {
        index++;
        if (index >= size) index = 0;
        changeImg()
    });
    addHandler(prev, "click", function () {
        index--;
        if (index < 0) {
            index = size - 1;
        }
        changeImg()
    });
    //点击圆点切换图片
    for (var d = 0; d < size; d++) {
        dots[d].setAttribute("data-id", d);
        addHandler(dots[d], "click", function () {
            index = this.getAttribute("data-id");
            changeImg();
        })
    }
    //菜单
    for (var j = 0; j < menus; j++) {
        menuItem[j].setAttribute("menu-id", j);
        addHandler(menuItem[j], "mouseover", function () {
            subMenu.className = "sub-menu";
            menuIndex = this.getAttribute("menu-id");
            for (var m = 0; m < innerBox.length; m++) {
                innerBox[m].style.display = "none";
            }
            innerBox[menuIndex].style.display = "block";
        });

    }

    startAutoPlay();
    var banner = byId("banner");
    //鼠标停在图片上，停止播放下一张图片
    addHandler(banner, "mouseover", stopAutoPlay);
    //鼠标离开图片，播放下一张图片
    addHandler(banner, "mouseout", startAutoPlay);
    //离开主菜单，子菜单消失
    addHandler(menuContent, "mouseout", function () {
        subMenu.className = "sub-menu hide";
    })
    //进入子菜单，子菜单显示停留
    addHandler(subMenu, "mouseover", function () {
        subMenu.className = "sub-menu";
    })
    //离开子菜单，消失
    addHandler(subMenu, "mouseout", function () {
        subMenu.className = "sub-menu hide";
    })

}
// 图片自动轮播
function startAutoPlay() {
    timer = setInterval(function () {
        index++;
        if (index >= size) {
            index = 0;
        }
        changeImg();
    }, 3000)
}
//清除定时器,停止自动播放
function stopAutoPlay() {
    if (timer) {
        clearInterval(timer);
    }
}

function changeImg() {
    for (var i = 0; i < size; i++) {
        pics[i].style.display = "none";
        dots[i].className = "";
    }
    pics[index].style.display = "block";
    dots[index].className = "active";
}


function addHandler(element, type, handler) {
    if (element.addEventListener) {
        element.addEventListener(type, handler, true);
    } else if (element.attachEventLinster) {
        element.attachEventLinster(type, handler)
    } else {
        element["on" + type] = handler;
    }
}

function byId(id) {
    return typeof (id) === "string" ? document.getElementById(id) : id;
}

addHandler(window, "load", slideImg);